package com.yunyao.web.controller.system;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.util.DateUtils;
import com.yunyao.common.config.JwtProperties;
import com.yunyao.common.constant.Constants;
import com.yunyao.common.constant.enums.DateFormatPattern;
import com.yunyao.common.core.base.BaseController;
import com.yunyao.common.core.redis.RedisCache;
import com.yunyao.common.dto.UserLoginDto;
import com.yunyao.common.sign.Md5Util;
import com.yunyao.common.web.util.ConvertUtil;
import com.yunyao.common.web.util.JwtUtil;
import com.yunyao.common.web.util.YResult;
import com.yunyao.framework.service.UserService;
import com.yunyao.framework.vo.user.LoginUserVO;
import com.yunyao.framework.vo.user.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author chenyejian
 * @date 2024-07-16
 */
@RestController
@RequestMapping("/system/userLogin")
public class LoginController extends BaseController {

    @Autowired
    JwtProperties jwtProperties;
    @Autowired
    private UserService userService;
    @Autowired
    private RedisCache redisCache;

    /**
     * 登录
     *
     * @param userLoginDto
     * @return 返回token
     */
    @PostMapping("/login")
    public JSONObject checkPassword(@RequestBody UserLoginDto userLoginDto) {
        JSONObject result = new JSONObject();
        result.put("success", false);
        try {
            //查询用户
            String md5Password = Md5Util.getMD5String(userLoginDto.getPassword());
            UserVO user = userService.checkPassword(userLoginDto, md5Password);
            if (user == null) {//用户名或密码错误
                result.put("msg", "用户名或密码错误");
                result.put("success", false);
                return result;
            } else {
                user = userService.getUserInfo(user.getId());
                //登录成功
                Map<String, Object> claims = new HashMap<>();
                claims.put("id", user.getId());
                claims.put("account", user.getAccount());
                String jwtToken = JwtUtil.createJWT(jwtProperties.getAdminSecretKey(),
                        jwtProperties.getAdminTtl(), claims);

                //往Redis中存储一个token的键值对
                redisCache.setCacheObject(Constants.TOKEN + jwtToken, user.getId(), 12,
                        TimeUnit.HOURS);
                redisCache.setCacheObject(Constants.USERID + user.getId(),
                        JSON.toJSONString(user), 12,
                        TimeUnit.HOURS);
                result.put("success", true);
                result.put("data", convertLoginUser(user, jwtToken));
                return result;
            }
        } catch (Exception e) {
            logger.error("登录失败", e);
            result.put("success", false);
            return result;
        }
    }

    /**
     * 注销
     *
     * @param userLoginDto
     * @return 返回token
     */
    @PostMapping("/loginOut")
    public YResult<Boolean> loginOut(UserLoginDto userLoginDto) {
        return null;
    }

    @PostMapping("/password/reset")
    public YResult<String> passwordReset() {
        return userService.passwordReset();
    }
    @GetMapping("/password/default")
    public YResult<String> passwordDefault() {
        return userService.passwordDefault();
    }

    private LoginUserVO convertLoginUser(UserVO user, String token) {
        LoginUserVO loginUser = new LoginUserVO();
        BeanUtils.copyProperties(user, loginUser);
        loginUser.setAccessToken(token);
        loginUser.setRefreshToken(token + "Refresh");
        loginUser.setUsername(user.getAccount());
        loginUser.setNickname(user.getRealName());
        loginUser.setIsProject(user.getIsProject());
        loginUser.setIsSupplier(user.getIsSupplier());
        loginUser.setNickname(user.getRealName());
        loginUser.setExpires(DateUtils.format(ConvertUtil.dateAdd(new Date(),
                Constants.DATE_TYPE_HOUR,
                12), DateFormatPattern.YEAR_MONTH_DAY_HOUR_MINUTE_SECOND.getPattern()));
        if (user.getRoleIds() != null) {
            loginUser.setRoleIds(user.getRoleIds().split(","));
        }
        return loginUser;
    }
}
